import axios from 'axios'
import userService, { User } from './user-service'

export const LOGIN_URL: string = '/auth/login'
export const LOGOUT_URL = '/auth/logout'
export const FETCH_USER_URL: string = '/auth/info'

class LoginService {
  login (username: string, password: string): Promise<User> {
    const data = new FormData()
    data.append('username', username)
    data.append('password', password)
    return axios.post<void>(LOGIN_URL, data).then(() => this.fetchUser())
  }

  logout (): Promise<void> {
    return axios.post<void>(LOGOUT_URL).then(() => {
      userService.username = ''
      userService.nickname = ''
      userService.authorities = []
    })
  }

  tryRelogin (): Promise<void> {
    return this.fetchUser()
      .catch(e => {
        /* ignore */
      })
      .then(() => {
        /* ignore */
      })
  }

  private fetchUser (): Promise<User> {
    return axios
      .get<User>(FETCH_USER_URL)
      .then(resp => resp.data)
      .then(user => {
        userService.username = user.username
        userService.nickname = user.nickname
        userService.authorities = [...user.authorities]
        return userService
      })
  }
}

export default new LoginService()
